package com.pucheng.bracelet.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.pucheng.bracelet.databinding.ItemListColorBinding
import me.hgj.jetpackmvvm.demo.app.ext.isNotNull

class ColorAdapter(private val callback: (position: Int, data: ColorData) -> Unit) :
    ListAdapter<ColorData, ColorHolder>(object : DiffUtil.ItemCallback<ColorData>() {
        override fun areItemsTheSame(oldItem: ColorData, newItem: ColorData): Boolean =
            oldItem.colorId == newItem.colorId

        override fun areContentsTheSame(oldItem: ColorData, newItem: ColorData): Boolean =
            oldItem == newItem

    }) {
    private var datas: ArrayList<ColorData>? = null
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ColorHolder {
        return ColorHolder(
            ItemListColorBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        ) {
            it?.apply {
                if (datas.isNotNull() && datas!!.size > this) {
                    for ((index, data) in datas!!.withIndex()) {
                        if (index != this) {
                            datas!![index].selected = false
                        }
                    }
                    callback.invoke(this, datas!![this])
                    notifyDataSetChanged()
                }
            }
        }
    }

    override fun onBindViewHolder(holder: ColorHolder, position: Int) {
        val item = getItem(position)
        item?.apply {
            holder.bind(this, position)
        }
    }

    override fun submitList(list: MutableList<ColorData>?) {
        datas = if (list != null) ArrayList(list) else null
        super.submitList(datas)
    }
}

class ColorHolder(private val binding: ItemListColorBinding,  callback: (position: Int?) -> Unit) :
    RecyclerView.ViewHolder(binding.root) {
    private var position: Int? = 0
    private var colorData: ColorData? = null

    init {
        binding.setOnSelectClickListener {
            colorData?.apply {
                colorData?.selected = !colorData?.selected!!
                bind(colorData, position)
                callback.invoke(position)
            }
        }
    }

    fun bind(colorData: ColorData?, position: Int?) {
        this.position = position
        this.colorData = colorData
        binding.apply {
            color = colorData
            executePendingBindings()
        }
    }

}

data class ColorData(
    val id: Int,
    var colorId: Int,
    var selected:Boolean
)
